package com.drojian.page5;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.drojian.demo.R;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class BaseFragment5 extends Fragment {
    private View view;
    private RecyclerView recyclerView;
    private ArrayList<Pojo> datas = new ArrayList<>();
    private ArrayList<Pojo> moreDatas = new ArrayList<>();
    private MyPage5Adapter adapter;
    private MyPage5Helper helper;
    private Banner banner;
    private int lastVisibleItem = 0;
    private final int COUNT = moreDatas.size();
    private SwipeRefreshLayout swipe_refresh_layout;
    private GridLayoutManager mLayoutManager;

    private Handler mHandler = new Handler(Looper.getMainLooper());


    public static BaseFragment5 newInstance() {
        return new BaseFragment5();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_base5, container, false);
        recyclerView = view.findViewById(R.id.page5_recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        banner = view.findViewById(R.id.page5_banner);
        swipe_refresh_layout = view.findViewById(R.id.swipe_refresh_layout);
        senRequest();
        getData();
        adapter = new MyPage5Adapter(getActivity(), datas,datas.size() > 0 ? true : false);
        recyclerView.setAdapter(adapter);
        mLayoutManager = new GridLayoutManager(getContext(), 1);
        recyclerView.setLayoutManager(mLayoutManager);
        int spacingInPixels = dpToPx( getContext(),3); // 假设你想要16dp的外边距，需要实现dpToPx转换方法
        recyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
        //添加分割线
        //recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        swipe_refresh_layout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipe_refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipe_refresh_layout.setRefreshing(false);
                    }
                }, 2000);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (adapter.isFadeTips() == false && lastVisibleItem + 1 == adapter.getItemCount()) {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                updateRecyclerView(adapter.getRealLastPosition(), adapter.getRealLastPosition() + COUNT);
                            }
                        }, 500);
                    }
                    if (adapter.isFadeTips() == true && lastVisibleItem + 2 == adapter.getItemCount()) {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                updateRecyclerView(adapter.getRealLastPosition(), adapter.getRealLastPosition() + COUNT);
                            }
                        }, 500);
                    }
                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
            }
        });

        return view;
    }



    public static int dpToPx(Context context, float dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5f); // 0.5f用于四舍五入
    }
    private void updateRecyclerView(int fromIndex, int toIndex) {
        getMoreData(StoreURL.MORE_JSON);
        if (moreDatas.size() > 0) {
            adapter.updateList(moreDatas, true);
        } else {
            adapter.updateList(null, false);
        }
    }

    private void getMoreData(String string) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL(string);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    JSONObject jsonObject = new JSONObject(response.toString());
                    JSONObject dataObject = jsonObject.getJSONObject("data");
                    JSONArray dataArray = dataObject.getJSONArray("datas");
                    for (int i = 0; i < dataArray.length(); i++) {
                        JSONObject itemObject = dataArray.getJSONObject(i);
                        String title = itemObject.getString("title");
                        String link = itemObject.getString("link");
                        String type = itemObject.getString("chapterName");
                        String data = itemObject.optString("niceShareDate");
                        String shareUser = itemObject.optString("author");
                        moreDatas.add(new Pojo(title,link,type,data,shareUser));
                    }
                    updateUI();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }



    public void senRequest() {
        getItemMessage(StoreURL.ITEM_JSON);
        getImageMessage(StoreURL.IMAGE_JSON);
        setBanner();
    }

    private  void  getItemMessage(String string){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL(string);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    storeData(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
    private void storeData(String string) {
        try {
            JSONObject jsonObject = new JSONObject(string);
            JSONObject dataObject = jsonObject.getJSONObject("data");
            JSONArray dataArray = dataObject.getJSONArray("datas");
            helper = new MyPage5Helper(getContext(), "database02.db", null, 1);
            SQLiteDatabase db = helper.getWritableDatabase();
            Cursor cursor = db.query("page1", null, null, null, null, null, null);
            ArrayList<String> titleList = new ArrayList<>();
            if(cursor.moveToFirst()){
                do{
                    int titleID = cursor.getColumnIndex("title");
                    String select_name = cursor.getString(titleID);
                    titleList.add(select_name);
                }while (cursor.moveToNext());
            }
            ContentValues values = new ContentValues();
            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject itemObject = dataArray.getJSONObject(i);
                String title = itemObject.getString("title");
                values.put("title",title);
                String link = itemObject.getString("link");
                values.put("origin",link);
                String type = itemObject.getString("chapterName");
                values.put("type",type);
                String data = itemObject.optString("niceShareDate");
                values.put("data",data);
                String shareUser = itemObject.optString("shareUser");
                values.put("shareUser",shareUser);
                if(titleList.contains(title)){
                    db.update("page1",values,"title = ?",new String[]{title});
                }else{
                    db.insert("page1",null,values);
                }
                values.clear();
            }
            updateUI();
        }catch (JSONException e) {
            e.printStackTrace();
        }

    }
    public void  getData(){
        MyPage5Helper helper1 = new MyPage5Helper(getContext(), "database02.db", null, 1);
        SQLiteDatabase db = helper1.getWritableDatabase();
        Cursor user = db.query("page1", null, null, null, null, null, null);
        if(user.moveToFirst()){
            do{
                int title1 = user.getColumnIndex("title");
                String title = user.getString(title1);
                int link1 = user.getColumnIndex("origin");
                String link = user.getString(link1);
                int type1 = user.getColumnIndex("type");
                String type = user.getString(type1);
                int data1 = user.getColumnIndex("data");
                String data = user.getString(data1);
                int shareUser1 = user.getColumnIndex("shareUser");
                String shareUser = user.getString(shareUser1);
                int image1 = user.getColumnIndex("image");
                int image = user.getInt(image1);
                datas.add(new Pojo(title,link,type,data,shareUser,image));
            }while (user.moveToNext());
        }

    }
    private  void  getImageMessage(String string){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL(string);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    getImagePath(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void getImagePath(String string) {
        ArrayList<String> pathList = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(string);
            JSONArray dataArray = jsonObject.getJSONArray("data");
            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject itemObject = dataArray.getJSONObject(i);
                pathList.add(itemObject.getString("imagePath"));
            }
            for (int i = 0; i < pathList.size(); i++) {
                saveImageFromUrl(pathList.get(i), getContext(),i);
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

    }

    private void saveImageFromUrl(String imageUrl, Context context,int i) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();

            InputStream input = connection.getInputStream();
            File dir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            File file = new File(dir, "downloaded_image" + i + ".jpg");

            // 检查文件是否存在，如果存在决定是否覆盖，true表示覆盖
            boolean overwrite = true;
            if (file.exists()) {
                if (!overwrite) {
                    return;
                } else {
                    if (!file.delete()) {
                        return;
                    }
                }
            }
            OutputStream output = new FileOutputStream(file, overwrite);
            byte[] buffer = new byte[1024];
            int read;
            while ((read = input.read(buffer)) != -1) {
                output.write(buffer, 0, read);
            }
            output.flush();
            output.close();
            input.close();
            updateUI();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public Bitmap getSavedImage(Context context,int i) {
        File directory = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File imageFile = new File(directory, "downloaded_image" + i + ".jpg");

        if (imageFile.exists()) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            // 设置options.inJustDecodeBounds = false; 来真正解码图片，仅设置true只会获取图片尺寸信息
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);
        } else {
            // 图片不存在时的处理
            return null;
        }
    }
    private void setBanner() {
        ArrayList<Bitmap> imageBitmap = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            imageBitmap.add(getSavedImage(getContext(), i));
        }
        banner.setAdapter(new BannerImageAdapter<Bitmap>(imageBitmap) {
            @Override
            public void onBindView(BannerImageHolder holder, Bitmap data, int position, int size) {
                holder.imageView.setImageBitmap(data);

            }
        });

    }
    private void updateUI() {
        getActivity().runOnUiThread(() -> {
            adapter.notifyDataSetChanged();
        });
    }


}